import pRightIcon from '@/orderSubPack/images/confirmOrder/right-icon.png';
import { Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import baseStyles from '../action-base.module.scss';

const GiftCardView = ({ dispatch, giftCardSelected, orgId, giftCardPrice }) => {
  const [isExistsGiftCard, setIsExistsGiftCard] = useState(false);

  // 获取提货券状态
  useEffect(() => {
    if (!orgId) {
      return;
    }

    dispatch({
      type: 'fineCard/fineCardGetCardList',
      payload: {
        status: 1,
        storeId: orgId,
        cardIds: giftCardSelected?.map(({ id }) => {
          return id;
        }),
      },
    }).then((res) => {
      const arr = res.filter((v) => Object.keys(v).length > 0);

      setIsExistsGiftCard(!!arr.length);
      // 设置选中的券
      return dispatch({
        type: 'productCar/setGiftCardSelect',
        payload: arr.filter(({ status }) => {
          return status === 1;
        }),
      });
    });
  }, [orgId]);

  return (
    <View className={baseStyles.ActionBase}>
      <View className="label customePageStyle">提货券：</View>
      <View
        className="action"
        onClick={() => {
          if (!orgId) {
            return;
          }

          Taro.navigateTo({
            url: '/giftCardSubPack/giftCardSelect/index?orgId=' + orgId,
          });
        }}
      >
        {giftCardSelected.length > 0 && (
          <>
            <View className="tip customePageStyle">- ¥ {parseFloat(giftCardPrice).toFixed(2)}</View>
            <Image src={pRightIcon} className="icon" />
          </>
        )}
        {giftCardSelected.length === 0 && isExistsGiftCard && (
          <>
            <View className="tip customePageStyle">有可用券</View>
            <Image src={pRightIcon} className="icon" />
          </>
        )}
        {giftCardSelected.length === 0 && !isExistsGiftCard && (
          <>
            <View className="tip disabled">暂无可用</View>
            <Image src={pRightIcon} className="icon" />
          </>
        )}
      </View>
    </View>
  );
};

export default connect(({ loading, productCar }) => ({
  loading,

  giftCardSelected: productCar.giftCardSelected,
}))(GiftCardView);
